package com.xinjian.jianba.utils.weixin;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

import com.xinjian.jianba.utils.DateUtil;

public class OrderNoUtils {
	private static AtomicInteger count = new AtomicInteger();
	/** 
	* 锁对象，可以为任意对象 
	*/
	private static Object lockObj = "lockerOrder";
	/** 
	 * 订单号生成计数器 
	 */
	private static long orderNumCount = 0L;
	/** 
	 * 每毫秒生成订单号数量最大值 
	 */
	private static int maxPerMSECSize = 1000;

	public static String generateUniqueId() {

		String uniqueId = ""; // 回写的订单号
		try {
			// 获取流水号
			int orderNmuber = getNumbers();
			if (orderNmuber == -1) { // 异常,循环取3次
				for (int i = 0; i < 3; i++) {
					orderNmuber = getNumbers();
					if (orderNmuber > 0) {
						break;
					}
				}
			}
			if (orderNmuber > 0) {
				// 格式化当前时间
				String dateNowStr = DateUtil.DateToString(new Date(), "yyyyMMddHHmmss");
				String orderNumberTmp = "000" + orderNmuber;// 补0
				uniqueId = dateNowStr + orderNumberTmp.substring(orderNumberTmp.length() - 3, orderNumberTmp.length());
			}
		} catch (Exception e) {
		}
		return uniqueId;
	}

	public static int getNumbers() {
		count.incrementAndGet();
		if (count.get() > 999) { // 超过1000，从1开始循环
			count.set(1);
		}
		return count.get();
	}

	/**  
	 * 生成订单编号  
	 * @return  
	 */
	public static synchronized String getOrderNo() {
		try {
			// 最终生成的订单号  
			String finOrderNum = "";
			synchronized (lockObj) {
				// 取系统当前时间作为订单号变量前半部分，精确到毫秒  
				long nowLong = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));
				// 计数器到最大值归零，可扩展更大，目前1毫秒处理峰值1000个，1秒100万  
				if (orderNumCount >= maxPerMSECSize) {
					orderNumCount = 0L;
				}
				//组装订单号  
				String countStr = maxPerMSECSize + orderNumCount + "";
				finOrderNum = nowLong + countStr.substring(1);
				orderNumCount++;
				// Thread.sleep(1000);  
			}
			return finOrderNum;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
//	public static void main(String[] args) {
//		System.err.println(generateUniqueId());
//	}
}
